import { reactive, onMounted, nextTick, computed, unref} from 'vue'
import type { Ref } from 'vue'
import { Columms } from '../types/column.ts'

export function useDesign(tableRef: Ref, colList: Array<Columms>, fixedWidthDefault: Ref) {
  const defaultConst = reactive({
    viewWidth: 360
  })
  // 屏幕宽度
  function getViewWidth(dom: Ref): number {
    if (!dom.value) {
      return defaultConst.viewWidth
    }
    const tableBlockStyle = window.getComputedStyle(dom.value)
    const width = +tableBlockStyle.width.replace('px', '')
    const paddingLeft = +tableBlockStyle.paddingLeft.replace('px', '')
    const paddingRight = +tableBlockStyle.paddingRight.replace('px', '')
    const widthSum = width - paddingLeft - paddingRight
    return !isNaN(widthSum) ? widthSum : defaultConst.viewWidth
  }
  
  onMounted(() => {
    nextTick(() => {
      defaultConst.viewWidth = getViewWidth(tableRef)
    })
  })

  // 要展示得列数
  const columnsList = computed(() => {
    return colList.filter(item => !item.hasChildren)
  })

   // 计算行宽
   const rowWidth = computed(() => {
    return columnsList.value.reduce((pre, cur) => {
      pre += cur.width ? +cur.width : fixedWidthDefault.value
      return pre
    }, 0)
  })

  // 左侧固定列
  const fixedLeftLength = computed(() => {
    const arr = columnsList.value.filter(item => item.fixed === 'left')
    return arr.length
  })

  // 中间列长度
  const centerColumnLength = computed(() => {
    return columnsList.value.filter(item => !['left', 'right'].includes(item.fixed)).length
  })

  // x轴宽度超出屏幕宽度
  const isXScroll = computed(() => {
    return rowWidth.value - defaultConst.viewWidth > 0
  })

  // 数组结构
  function unRefArr (obj: any) {
    return Object.keys(obj).reduce((pre: any, key) => {
      pre[key] = unref(obj[key])
      return pre
    }, {})
  }
  return unRefArr({
    fixedLeftLength,
    centerColumnLength,
    isXScroll
  })
}